import 'package:flutter/material.dart';

/// https://juejin.cn/post/7205826220063031353
class DraggableDemo extends StatefulWidget {
  const DraggableDemo({super.key});

  @override
  State<StatefulWidget> createState() => _DraggableDemoState();

}

class _DraggableDemoState extends State<DraggableDemo> {

  Map<String, List<String>> data = {
    "List A" : ['A1', 'A2', 'A3', 'A4','A5','A6'],
    "List B" : ['B1', 'B2', 'B3', 'B4','B5','B6'],
  };

  String? movingValue;

  @override
  Widget build(BuildContext context) {
    List<Widget> children = [];

    data.forEach((key, list) {
      children.add(Text(key));
      children.add(GridView(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 5.0,
              crossAxisSpacing: 5.0,
              childAspectRatio: 1),
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          children: buildItems(list)
      ));
      children.add(const SizedBox(height: 20,));
    });

    return Scaffold(
      appBar: AppBar(title: const Text('Draggable Demo')),
      body: SingleChildScrollView(child: Column(children: children))
    );
  }

  // 生成GridView的items
  List<Widget> buildItems(List<String> list) {
    List<Widget> items = [];
    for (String title in list)  {
      items.add(Center(child: draggableItem(title),));
    }
    return items;
  }

  // 生成可拖动的item
  Widget draggableItem(String value) {
    return Draggable(
      data: value,
      feedback: baseItem(value),
      childWhenDragging: null,
      onDragStarted: () {
        setState(() {
          movingValue = value;//记录开始拖拽的数据
        });
      },
      onDraggableCanceled: (Velocity velocity, Offset offset) {
        setState(() {
          movingValue = null;//清空标记进行重绘
        });
      },
      child: DragTarget(
        builder: (context, candidateData, rejectedData) {
          return baseItem(value);
        },
        onWillAccept: (moveData) {
          var accept = moveData != null;
          if (accept) {
            exchangeItem("$moveData", value, false);
          }
          return accept;
        },
        onAccept: (moveData) {
          exchangeItem("$moveData", value, true);
        },
      ),
    );
  }


  Widget baseItem(String value) {
    if (value == movingValue) {
      return Container();
    }
    return Container(
      width: 110,
      height: 110,
      color: Colors.blue,
      child: Center(
        child: Text(
          value,
          textAlign: TextAlign.center,
          style: const TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 20,
              color: Colors.yellowAccent),
        ),
      ),
    );
  }

  // 重新排序
  void exchangeItem(String moveData, String toData, bool onAccept) {
    setState(() {
      for (List<String> list in data.values) {
        if (list.contains(moveData)) {
          if (list.contains(toData)) {
            int toIndex = list.indexOf(toData);
            list.remove(moveData);
            list.insert(toIndex, moveData);
          } else {
            var toList = [];
            for (var value in data.values) {
              if (value.contains(toData)) {
                toList = value;
                break;
              }
            }
            int toIndex = toList.indexOf(toData);
            list.remove(moveData);
            toList.insert(toIndex, moveData);
          }
          break;
        }
      }

      if (onAccept) {
        movingValue = null;
      }
    });
  }
}

